package curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * Created by Lenovo on 2018/11/22.
 */
public class CuratorTest {
    private static final String CONNECT_ADDR = "10.1.66.76:2181";
    //会话超时时间
    private static final int SESSION_TIMEOUT = 6000;
    //连接超时时间
    private static final int CONNECTION_TIMEOUT = 1000;

    static RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 10);
    CuratorFramework curatorFramework = null;

    public static void main(String[] args) throws Exception{
        //创建zk连接  链式编程方式
        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder().connectString(CONNECT_ADDR).sessionTimeoutMs(SESSION_TIMEOUT).connectionTimeoutMs(CONNECTION_TIMEOUT).retryPolicy(retryPolicy).build();
        //开启连接
        curatorFramework.start();
        //创建节点
        //curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/parent/child", "aaa".getBytes());
        //删除节点, guaranteed保证机制，出错后后台删除 直到删除成功
        //curatorFramework.delete().guaranteed().deletingChildrenIfNeeded().forPath("/parent");
        //获取子节点
        /*
        List<String> nodes = curatorFramework.getChildren().forPath("/parent");
        for(String node : nodes){
            System.out.println("子节点名称：" + node);
            System.out.println("子节点内容：" + new String(curatorFramework.getData().forPath("/parent/" + node)));
        }
        */
        //设置节点
        //curatorFramework.setData().forPath("/parent/child", "abc".getBytes());
        //判断节点是否存在
        /*
        Stat stat = curatorFramework.checkExists().forPath("/parent");
        System.out.println(stat);
        */
        /*
        //设置节点信息回调
        ExecutorService executorService = Executors.newCachedThreadPool();
        curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).inBackground(new BackgroundCallback() {
            public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
                System.out.println(curatorFramework.getZookeeperClient());
                System.out.println(curatorEvent.getResultCode());
                System.out.println(curatorEvent.getType());
                System.out.println(curatorEvent.getPath());
                System.out.println(curatorEvent.getContext());
                System.out.println(curatorEvent.getData().toString());
                System.out.println(Thread.currentThread().getName());
            }
        },executorService).forPath("/parentNode/a1", "aaa".getBytes());
        Thread.sleep(5000);
        */


        //建立一个cache缓存
        final NodeCache cache = new NodeCache(curatorFramework,"/note_curator");
        cache.start(true);
        cache.getListenable().addListener(new NodeCacheListener() {
            /**
             * 方法名称：nodeChanged
             * 概要说明：触发时间为创建节点和更新节点，在删除节点的时候并不会触发此操作
             */
            @Override
            public void nodeChanged() throws Exception {
                System.out.println(new String(cache.getCurrentData().getData()));
                System.out.println(cache.getCurrentData().getPath());
            }
        });
        Thread.sleep(Integer.MAX_VALUE);




        //关闭连接
        curatorFramework.close();
    }

    public void nodeClildrenListen() throws Exception {
        //createSession();
        //建立一个PathChildrenCache缓存，第三个参数为是否接收节点数据内容，如果为false则不接收
        final PathChildrenCache cache = new PathChildrenCache(curatorFramework,"/note_curator",true);
        //在初始化的时候就进行缓存监听
        cache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
        cache.getListenable().addListener(new PathChildrenCacheListener() {
            /**
             *方法名称：childEvent  监听子节点变更
             *概要说明：新建、修改、删除
             */
            @Override
            public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
                switch (pathChildrenCacheEvent.getType()){
                    case CHILD_ADDED:
                        System.out.println("add children");
                        System.out.println(new String(pathChildrenCacheEvent.getData().getData()));
                        System.out.println(new String(pathChildrenCacheEvent.getData().getPath()));
                        break;
                    case CHILD_REMOVED:
                        System.out.println("remove children");
                        System.out.println(new String(pathChildrenCacheEvent.getData().getData()));
                        System.out.println(new String(pathChildrenCacheEvent.getData().getPath()));
                        break;
                    case CHILD_UPDATED:
                        System.out.println("update children");
                        System.out.println(new String(pathChildrenCacheEvent.getData().getData()));
                        System.out.println(new String(pathChildrenCacheEvent.getData().getPath()));
                        break;
                }
            }
        });
        Thread.sleep(Integer.MAX_VALUE);
    }
}
